<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable">
      <template #tableTop v-if="isShowHint">
        <div class="weight-hint">当前基础定额影响因子的权重之和不等于100</div>
      </template>
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:caret-down-outlined" @click="handleInit"> 初始化</a-button>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd"> 新增</a-button>
        <a-button type="primary" @click="editListFn" preIcon="ant-design:plus-outlined" v-if="!startEdit">批量编辑</a-button>
        <a-button type="primary" @click="saveListFn" v-if="startEdit">保存</a-button>
        <a-button type="default" @click="editCancel" preIcon="ant-design:close-outlined" v-if="startEdit">取消</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template #bodyCell="{ column, text, record }">
        <!-- 下拉框插槽(基础定额影响因子) -->
        <template v-if="column.editRow && column.dataIndex === 'factorCode'">
          <a-select v-if="startEdit || record.isAdd" v-model:value="record['factorCode']" style="width: 100%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" :options="quotaSelectOptions" :fieldNames="{ label: 'factorName', value: 'factorCode' }" @change="(e, record) => factorChange(e, record)" />
          <span v-else>
            {{ record['factorName'] }}
          </span>
        </template>
        <template v-if="column.editRow && column.dataIndex === 'factorWeight'">
          <a-input-number v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" addon-after="%" :min="0" />
          <span v-else>
            {{ text }}
          </span>
        </template>
        <template v-if="column.editRow && column.dataIndex === 'integralValue'">
          <a-input-number v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" addon-after="分" :min="0" />
          <span v-else>
            {{ text }}
          </span>
        </template>
        <template v-if="column.editRow && column.dataIndex === 'displayOrder'">
          <a-input-number v-if="startEdit || record.isAdd" v-model:value="record[column['dataIndex']]" :min="0" />
          <span v-else>
            {{ text }}
          </span>
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <HubTeamQuotaOrgModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="emp-hubTeamQuotaOrg" setup>
import { reactive, ref,onMounted } from 'vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import HubTeamQuotaOrgModal from './components/HubTeamQuotaOrgModal.vue'
import { columns, searchFormSchema } from './HubTeamQuotaOrg.data';
import { list, deleteOne, getImportUrl, getExportUrl, updateBatch, getQuotaList, init } from './HubTeamQuotaOrg.api';
const queryParam = reactive<any>({});
//注册model
const [registerModal, { openModal }] = useModal();
import { useMessage } from '/@/hooks/web/useMessage'; // 轻提醒
const { createMessage: $message } = useMessage();
import { useRoute } from 'vue-router';



//注册table数据
const { tableContext, } = useListPage({
  tableProps: {
    title: '基础定额配置',
    api: list,
    columns,
    canResize: false,
    showIndexColumn: true,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
    immediate: true,   //不自动请求
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },
    afterFetch: (list) => {
      let num = 0;
      list.forEach((i) => {
        if (i.factorWeight) {
          num += parseFloat(i.factorWeight);
        }
      });
      isShowHint.value = num != 100;
    },
  },
  exportConfig: {
    name: "基础定额配置-班组详情",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})

const [registerTable, { reload, getDataSource, getForm }, { selectedRowKeys }] = tableContext

//个性化参数
const showActionColumn = ref(true);
const isShowHint = ref(false);
//控制按钮显示与隐藏
let startEdit = ref(false);
//初始化因子下拉框
const quotaSelectOptions = ref([
  { factorCode: '', factorName: '' }
]);
const route = useRoute();

// 默认执行一次
onMounted(async () => {
  getQuotaSelectOptions();
  //路由携带参数
  let query = route.query;
});

/**
 * 初始化事件
 */
function handleInit() {
  let formData = getForm().getFieldsValue();
  console.log(formData);
  init(
    { orgCode: formData.orgCode }
  ).then((res) => {
    if (res) {
      handleSuccess();
    }
  });
}

/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}

// 批量编辑回调
function editListFn() {
  startEdit.value = true;
}

function nameMapByCode(options, tabList) {
  options.forEach((org) => {
    tabList.forEach((item) => {
      if (item.factorCode == org.factorCode) {
        item.factorName = org.factorName;
        item.saveCode = org.saveCode;
      }
    });
  });
}

// 保存回调
async function saveListFn() {
  const data = getDataSource();
  nameMapByCode(quotaSelectOptions.value, data);
  // quotaSelectOptions.value.forEach(org => {
  //   data.forEach(item => {
  //     if (item.factorCode == org.factorCode) {
  //       item.factorName = org.factorName
  //     }
  //   })
  // })
  // let factorList = await getQuotaList(orgNameBase.value)
  // console.log('factorList', factorList)
  let num = 0;
  let saveFlag = false;
  let saveMsg = '';
  data.forEach((item) => {
    if (!item.factorName) {
      saveFlag = true;
      saveMsg = '基础定额影响因子不能为空';
      return;
    }
    console.log('111');
    if (item.factorWeight == 0 || !item.factorWeight) {
      saveFlag = true;
      saveMsg = '基础定额影响因子权重不能小于0';
      return;
    }
    if (!item.integralValue) {
      saveFlag = true;
      saveMsg = '单个设备积分值不能为空';
      return;
    }
    num += parseFloat(item.factorWeight);
    // delete item.editId;
  });
  if (saveFlag) {
    $message.warning(saveMsg);
    return;
  }
  isShowHint.value = num != 100;
  // if (num != 100) {
  //   // $message.warning('基础定额影响因子权重之和应改等于100');
  //   // num = 0
  //   // return
  //   isShowHint.value = true
  // } else {

  // }
  const list = {
    datas: data,
  };
  await updateBatch(list); // 更新数据
  await reload(); // 保存数据
  startEdit.value = false;
}


// 取消回调
async function editCancel() {
  startEdit.value = false;
  showActionColumn.value = true;
  let records = getDataSource();
  records.forEach((item) => {
    delete item.editId;
  });
  for (const r of records) {
    try {
      await r.onEdit(false, false);
    } catch (e) { }
  }
  await reload();
  $message.info('已取消');
}

// 下拉框数据
function getQuotaSelectOptions() {
  getQuotaList().then((res) => {
    quotaSelectOptions.value = res;
  });
}

/**
 * 基础定额因子下拉框change事件
 */
function factorChange(e, record) {
  quotaSelectOptions?.value.forEach((item) => {
    if (item.factorCode == e) {
      record.factorName = item.factorName;
    }
  });
}

/**
 * 表格操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      icon: 'clarity:note-edit-line',
      onClick: handleEdit.bind(null, record)
    },
    {
      label: '删除',
      icon: 'ant-design:delete-outlined',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        placement: 'left',
        confirm: handleDelete.bind(null, record),
      }
    }
  ]
}
</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}

.weight-hint {
  // margin: -4px 0 -2px;
  // padding-top: 5px;
  padding-left: 12px;
  height: 38px;
  background-color: #f3f3f3;
  border-color: #e3e3e3;
  line-height: 38px;
  color: red;
}
</style>